<template>
    <el-table :data="data" :style="style" :height="height" :border="true" :stripe="true" class="lemon-table" row-key="id" :tree-props="{ children: children, hasChildren: 'hasChildren' }" default-expand-all>
        <el-table-column v-for="(item, index) in tableItem" :prop="item.prop" :label="item?.label" :width="item?.width" :min-width="item?.minWidth" :formatter="item?.formatter" :show-overflow-tooltip="item?.tooltip ? item?.tooltip : true" :key="index" />
        <slot name="columns"></slot>
        <el-table-column fixed="right" v-show="showOperate" label="操作" :width="operateWidth + 'px'" :align="'center'" :key="operateKey">
            <template #default="scope">
                <div class="operate-div" ref="operateColRef">
                    <!-- 定义插槽-自定义按钮 -->
                    <slot name="frontBtn" :row="scope.row"></slot>
                    <el-button type="info" :size="size" @click="onInfo(scope.row)" v-if="showInfo" v-has-permission="infoPermission">详情</el-button>
                    <el-button type="primary" :size="size" @click="onEdit(scope.row)" v-if="showEdit" v-has-permission="editPermission">编辑</el-button>
                    <el-button type="success" :size="size" @click="onEnable(scope.row)" v-if="scope.row.status == 0 && showEnable" v-has-permission="enablePermission">启用</el-button>
                    <el-button type="warning" :size="size" @click="onUnable(scope.row)" v-if="scope.row.status == 1 && showUnable" v-has-permission="unablePermission">停用</el-button>
                    <el-button type="danger" :size="size" @click="onDel(scope.row)" v-if="showDel" v-has-permission="delPermission">删除</el-button>
                    <!-- 定义插槽-自定义按钮 -->
                    <slot name="afterBtn" :row="scope.row"></slot>
                </div>
            </template>
        </el-table-column>

        <!-- 空状态 -->
        <template #empty>
            <el-empty description="暂无数据，请刷新试试！" />
        </template>
    </el-table>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, onUnmounted, nextTick } from "vue";
import { debounce } from "lodash-es";
import type { ComponentSize } from "element-plus";

//接收父类传过来的参数
interface Props {
    data?: Array<any>;
    style?: Record<string, any>;
    height?: string | number;
    tableItem?: Array<any>;
    showInfo?: boolean;
    showEdit?: boolean;
    showEnable?: boolean;
    showUnable?: boolean;
    showDel?: boolean;
    infoPermission?: string;
    editPermission?: string;
    enablePermission?: string;
    unablePermission?: string;
    delPermission?: string;
    children?: string;
    isTree?: boolean;
}
const props = withDefaults(defineProps<Props>(), {
    data: () => [],
    style: () => ({}),
    height: "auto",
    tableItem: () => [],
    showInfo: true,
    showEdit: true,
    showEnable: true,
    showUnable: true,
    showDel: true,
    infoPermission: "FINDBYID",
    editPermission: "UPDATE",
    enablePermission: "ENABLE",
    unablePermission: "UNABLE",
    delPermission: "DELETEBYID",
    children: "children",
    isTree: false,
});

//按钮大小
const size = ref<ComponentSize>("default");

//使用defineEmits注册一个自定义事件,子传父
const emit: any = defineEmits(["onInfo", "onEdit", "onEnable", "onUnable", "onDel"]);
const onInfo = (row: any) => emit("onInfo", row);
const onEdit = (row: any) => emit("onEdit", row);
const onEnable = (row: any) => emit("onEnable", row);
const onUnable = (row: any) => emit("onUnable", row);
const onDel = (row: any) => emit("onDel", row);

//操作列的宽度
const operateWidth = ref(0);

//是否展示操作列
const showOperate = ref(true);

//操作列宽度的ref
const operateColRef = ref<HTMLElement | null>(null);

//监听 data 发生变化 或操作列发生变化时
watch(
    [() => props.data ?? [], () => operateColRef.value],
    async () => {
        await nextTick(); // 等待 DOM 更新
        debounceSetOperateWidth(); //防抖，避免多次执行
    },
    { immediate: true, deep: true }
);

//防抖执行
const debounceSetOperateWidth = debounce(() => setOperateWidth(), 100);

//设置操作列的宽度
const setOperateWidth = () => {
    //操作列的按钮
    const buttons = document.querySelector(".operate-div")?.querySelectorAll("button");

    //宽度
    let width = 0;
    buttons?.forEach((item: any) => {
        width += item.clientWidth;
        width += 15; //按钮的margin-left: 12px;
    });

    if (width == 0) {
        showOperate.value = false;
    } else {
        operateWidth.value = width + 20;
    }
};

//操作列的key
const operateKey = ref<string>(`operate-${new Date().getTime()}`);

const handleClick = (_event: MouseEvent) => {
    operateKey.value = `operate-${new Date().getTime()}`;
};

onMounted(() => {
    document.addEventListener("click", handleClick);
});

onUnmounted(() => {
    document.removeEventListener("click", handleClick);
    debounceSetOperateWidth.cancel();
});
</script>

<style scoped lang="less">
.lemon-talbe {
    width: 100%;
}

.el-table :deep(.cell) {
    white-space: nowrap !important;
}

.operate-div {
    white-space: nowrap;
    display: inline-block;
}
</style>
